package com.wnxy.admin.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import com.wnxy.admin.common.ResponseResult;
import com.wnxy.admin.dto.JChargingPileDto;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wnxy.admin.entity.AlarmSettings;
import com.wnxy.admin.service.IAlarmSettingsService;
import com.wnxy.admin.vo.AlertEnum;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import com.wnxy.admin.entity.ChargingPile;
import com.wnxy.admin.service.IChargingPileService;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 充电桩 前端控制器
 * </p>
 *
 * @author All
 * @since 2023-11-29
 */
@CrossOrigin
@RestController
@RequestMapping("/charging-pile")
public class ChargingPileController {

    private final IChargingPileService chargingPileServiceImpl;
    private final IAlarmSettingsService alarmSettingsServiceImpl;
    private final RabbitTemplate rabbitTemplate;
    public ChargingPileController(IChargingPileService chargingPileServiceImpl, IAlarmSettingsService alarmSettingsServiceImpl, RabbitTemplate rabbitTemplate){
        this.chargingPileServiceImpl = chargingPileServiceImpl;
        this.alarmSettingsServiceImpl = alarmSettingsServiceImpl;
        this.rabbitTemplate = rabbitTemplate;
    }

    @GetMapping("/all")
    public ResponseResult<List<ChargingPile>> all(){
        List<ChargingPile> list = chargingPileServiceImpl.list();
        return ResponseResult.ok(list);
    }

    @PostMapping("/findByPage")
    public ResponseResult<PageInfo<JChargingPileDto>> findByPage(@RequestBody Map<String,Object> params){
        String chargingPileName = (String) params.get("chargingPileName");
        Integer pageNum = (Integer) params.get("pageNum");
        Integer pageSize = (Integer) params.get("pageSize");
        //2.调用业务层
        PageInfo<JChargingPileDto> pageInfo = chargingPileServiceImpl.findByPage(chargingPileName,pageNum,pageSize);
        //3.返回结果
        return ResponseResult.ok(pageInfo);
    }

    @PostMapping("/save")
    public ResponseResult save(@RequestBody ChargingPile chargingPile){
        chargingPile.setChargingGunAmount(2);
        chargingPile.setChargingPower("96 kW");
        chargingPile.setChargingPileState("空闲");
        chargingPileServiceImpl.save(chargingPile);
        List<AlarmSettings> settings = new ArrayList<>();

        AlarmSettings alarmSettings = new AlarmSettings();
        alarmSettings.setAlarmName(AlertEnum.DEVICE_OFFLINE.getMsg());
        alarmSettings.setChargerId(chargingPile.getId());
        alarmSettings.setStationId(chargingPile.getChargingStationId());
        alarmSettings.setAlarmLevel(-1);
        alarmSettings.setStatus(1);
        alarmSettings.setFlag(0);

        AlarmSettings alarmSettings2 = new AlarmSettings();
        alarmSettings2.setAlarmName(AlertEnum.POWER_ALARM.getMsg());
        alarmSettings2.setChargerId(chargingPile.getId());
        alarmSettings2.setStationId(chargingPile.getChargingStationId());
        alarmSettings2.setAlarmLevel(0);
        alarmSettings2.setStatus(1);
        alarmSettings2.setFlag(0);

        AlarmSettings alarmSettings3 = new AlarmSettings();
        alarmSettings3.setAlarmName(AlertEnum.COMMUNICATION_ABNORMALITY.getMsg());
        alarmSettings3.setChargerId(chargingPile.getId());
        alarmSettings3.setStationId(chargingPile.getChargingStationId());
        alarmSettings3.setAlarmLevel(1);
        alarmSettings3.setStatus(1);
        alarmSettings3.setFlag(0);

        Collections.addAll(settings, alarmSettings, alarmSettings2, alarmSettings3);
        alarmSettingsServiceImpl.addBatchAlarmSetting(settings);
        return ResponseResult.ok();
    }

    @PostMapping("/update")
    public ResponseResult<Integer> update(@RequestBody JChargingPileDto jChargingPileDto){
        int row = chargingPileServiceImpl.updateById(jChargingPileDto);
        return ResponseResult.ok(row);
    }

    @GetMapping("/delete")
    public ResponseResult delete(Long id){
        alarmSettingsServiceImpl.removeAlarmSetting(id);
        chargingPileServiceImpl.removeById(id);
        return ResponseResult.ok();
    }

    @PostMapping("/deleteBatch")
    public ResponseResult deleteBatch(@RequestBody String[] ids){
        for (String id : ids) {
            alarmSettingsServiceImpl.removeAlarmSetting(Long.valueOf(id));
        }
        chargingPileServiceImpl.removeBatchByIds(Arrays.asList(ids));
        return ResponseResult.ok();
    }

    @PostMapping("/updateBy/{id}")
    public ResponseResult updateBy(@PathVariable Long id){
        ChargingPile chargingPile = new ChargingPile();
        UpdateWrapper<ChargingPile> wrapper = new UpdateWrapper<>();
        wrapper.lambda()
                .eq(ChargingPile::getId,id)
                .set(ChargingPile::getChargingPileState, "预约")
                .eq(ChargingPile::getChargingPileState, "空闲");
        chargingPileServiceImpl.update(chargingPile,wrapper);
        return ResponseResult.ok();
    }

    /* updatePileStateById接口测试 [2023-12-02 可删除] */
    @PostMapping("/updateById")
    public ResponseResult updateBy(Long id, String pieState){
        chargingPileServiceImpl.updatePileStateById(id, pieState);
        ChargingPile chargingPile = chargingPileServiceImpl.getOne(Wrappers.lambdaQuery(ChargingPile.class)
                .eq(ChargingPile::getId, id));
        return ResponseResult.ok(chargingPile);
    }

    /* switchPileState接口测试 [2023-12-07 可删除] */
    @PutMapping("/switchPileState")
    public ResponseResult switchPileState(String chargingPileNumber, String pileState) {
        chargingPileServiceImpl.switchPileState(chargingPileNumber, pileState);
        ChargingPile chargingPile = chargingPileServiceImpl.getOne(Wrappers.lambdaQuery(ChargingPile.class)
                .eq(ChargingPile::getChargingPileNumber, chargingPileNumber));
        return ResponseResult.ok(chargingPile);
    }

    /**
     * 禁用充电桩
     */
    @PostMapping("/disabled")
    public ResponseResult disabledChargingPile(Long id){
        LambdaUpdateWrapper<ChargingPile> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ChargingPile::getId,id).set(ChargingPile::getChargingPileState,"离线");
        chargingPileServiceImpl.update(wrapper);
        return ResponseResult.ok();
    }

    /**
     * 导出Excel
     */
    @GetMapping("/export")
    public void exportData(HttpServletResponse response) throws IOException {
        //1.调用业务层获取要导出数据
        List<JChargingPileDto> list = chargingPileServiceImpl.listDto();
        //2.设置响应头，指定下载文件
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //文件名最好不使用汉字，否则需要进行编码，文件名会有乱码。告诉浏览器，这个文件要下载，并且指定文件名
        response.setHeader("content-disposition", "attachment;filename=JChargingPileDto.xlsx");
        //3.调用EasyExcel的方法导出文件
        //获取响应输出流
        ServletOutputStream out = response.getOutputStream();
        //参数：输出流，实体类
        EasyExcel.write(out, JChargingPileDto.class)
                .sheet("充电桩表")  //工作簿名字
                .doWrite(list);   //要写出的数据列表
    }

    /**
     * 导入Excel
     */
    @SneakyThrows
    @PostMapping("/import")
    public ResponseResult importFile(@RequestPart MultipartFile file){
        //通过EasyExcel读取上次的文件内容，并转换为Building集合
        List<ChargingPile> chargingPiles = EasyExcel.read(file.getInputStream())
                .head(ChargingPile.class)
                .sheet()
                .doReadSync();//同步读取，如果没有读完，程序不会向下执行

        //循环遍历buildings，清除空行转换过来的building
        chargingPiles = chargingPiles.stream()
                .filter(b -> b.getChargingPileName() != null && b.getChargingPileNumber().length() > 0)
                .collect(Collectors.toList());

        //逐个添加，有效的就提交，无效的就下一个，不需要走同一个事务
        int count = 0; //成功插入的数量
        for (ChargingPile chargingPile : chargingPiles) {
            try {
                chargingPileServiceImpl.save(chargingPile);
                count++;
            } catch (Exception e) {
            }
        }

        return ResponseResult.ok(count);
    }

}
